<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/3/29
 * Time: 上午11:40
 */

namespace backend\models;

use common\models\MobileCoupon;
use common\models\MobileUser;
use common\models\MobileUserCoupon;
use common\models\User;
use common\models\UserCoupon;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQuery;

/**
 *
 * @property ActiveQuery $query
 */
class UserCouponSearch extends UserCoupon
{
    public $channelId;
    public $startTime;
    public $endTime;
    public $query;
    public $catalog;
    public $mobile;

    public function rules()
    {
        return [
            [['status', 'catalog'], 'integer'],
            [['startTime', 'endTime', 'mobile'], 'string']
        ];
    }


    public function search($params)
    {
        $this->query = UserCoupon::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $this->query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC]], // 新增配置项 默认 id 倒序
        ]);
        if (!$this->load($params)) {
            return $dataProvider;
        }

        if (isset($this->startTime) && $this->startTime !== '') {
            $this->setStartTime();
        }

        if (isset($this->endTime) && $this->endTime !== '') {
            $this->setEndTime();
        }

        if (isset($this->catalog) && $this->catalog !== '') {
            $this->setCatalog();
        }
        if (isset($this->mobile) && $this->mobile !== '') {
            $this->setMobile();
        }

        return $dataProvider;
    }

    private function setStartTime()
    {
        $this->query->andWhere(['>', 'updated_at', strtotime($this->startTime . " 00:00:00")]);
    }

    private function setEndTime()
    {
        $this->query->andWhere(['<', 'updated_at', strtotime($this->endTime . " 23:59:59")]);
    }

    public function setCatalog()
    {
        $this->query->andWhere(['catalog' => $this->catalog]);
    }

    public function setMobile()
    {
        $user = User::find()->where(['phone' => $this->mobile])->one();
        if ($user != null) {
            $this->query->andWhere(['user_id' => $user->id]);
        } else {
            $this->query->andWhere(['user_id' => 0]);
        }
    }
}
